package com.shanzmoo.platform.server.api.web.sys;

import cn.hutool.core.bean.BeanUtil;
import com.shanzmoo.base.bean.SHttpResponse;
import com.shanzmoo.base.constant.Constant;
import com.shanzmoo.db.module.merchant.entity.MerchantInfoEntity;
import com.shanzmoo.db.module.merchant.service.IMerchantInfoService;
import com.shanzmoo.platform.server.api.domain.AuthUser;
import com.shanzmoo.platform.server.api.domain.bo.LoginReqBO;
import com.shanzmoo.platform.server.api.domain.vo.AuthUserVo;
import com.shanzmoo.platform.server.api.manager.JwtManager;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

@Slf4j
@Api(tags = "系统登录")
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class LoginController {
    private final AuthenticationManager authenticationManager;
    private final JwtManager jwtManager;
    private final IMerchantInfoService iMerchantInfoService;
    private AuthUserVo getAuthUserLogin(String mobile, String password){
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(mobile, password));
        SecurityContextHolder.getContext().setAuthentication(authentication);
        AuthUser authUser = BeanUtil.toBean(authentication.getPrincipal(),AuthUser.class);
        String jwt = jwtManager.createJWT(false, authUser.getUserId(), authUser.getUsername());
        MerchantInfoEntity user = iMerchantInfoService.lambdaQuery().eq(MerchantInfoEntity::getMobile,mobile).one();
        AuthUserVo userVo = new AuthUserVo();
        userVo.setUserId(user.getId());
        userVo.setMobile(user.getMobile());
        userVo.setToken(jwt);
        return userVo;
    }

    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public SHttpResponse<AuthUserVo> login(@Valid @RequestBody LoginReqBO loginReq) {
        return SHttpResponse.ok(getAuthUserLogin(loginReq.getMobile(),loginReq.getPassword()));
    }

    @ApiOperation(value = "退出")
    @PostMapping("/logout")
    public SHttpResponse<Boolean> logout() {
        try {
            // 从redis中删除jwt信息
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                    .getRequestAttributes()).getRequest();
            jwtManager.invalidateJWT(request);
        } catch (SecurityException e) {
            return SHttpResponse.fail(Constant.ERRCODE_LOGIC, "退出异常");
        }
        return SHttpResponse.ok();
    }
}
